package com.bigdata.service.service;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.amazonaws.util.Md5Utils;
import com.bigdata.common.constant.CacheConstants;
import com.bigdata.common.constant.Constants;
import com.bigdata.common.core.domain.entity.SysUser;
import com.bigdata.common.core.domain.model.LoginUser;
import com.bigdata.common.enums.DeviceType;
import com.bigdata.common.enums.LoginType;
import com.bigdata.common.helper.LoginHelper;
import com.bigdata.common.utils.MessageUtils;
import com.bigdata.common.utils.StringUtils;
import com.bigdata.common.utils.redis.RedisUtils;
import com.bigdata.service.domain.bo.ServiceUsersBo;
import com.bigdata.service.domain.vo.ServiceUsersVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Service
public class AppLoginService {


    @Autowired
    private IServiceUsersService serviceUsersService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String uuid, String code) {

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedisUtils.getCacheObject(verifyKey);
        RedisUtils.deleteObject(verifyKey);
        if (StringUtils.isBlank(captcha)) {
            throw new RuntimeException("验证码已过期");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new RuntimeException("验证码错误");
        }
        ServiceUsersBo bo = new ServiceUsersBo();
        bo.setUsername(username);
        // 框架登录不限制从什么表查询 只要最终构建出 LoginUser 即可
        List<ServiceUsersVo> userList = serviceUsersService.queryList(bo);
        if (userList.size() == 0) {
            throw new RuntimeException("用户名或密码错误");
        }
        ServiceUsersVo user = userList.get(0);
        String pwd = Md5Utils.md5AsBase64(password.getBytes());
        log.info("pwd:{}", pwd);
        if(!pwd.equals(user.getPasswordHash())) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(user.getUserId());
        loginUser.setUsername(user.getUsername());
        loginUser.setUserType("app_user");
        // 生成token
        LoginHelper.loginByDevice(loginUser, DeviceType.APP);


        return StpUtil.getTokenValue();
    }

    public ServiceUsersVo selectUserById(Long userId) {
        return serviceUsersService.queryById(userId);
    }
}
